﻿// ----------------------------------------------------------------------
// <author name="Moses Kehengu"/>
// <copyright file="ReportingManagement.cs" company="Futures Group International">
//     Copyright statement. All right reserved
// </copyright>
//
// ------------------------------------------------------------------------

using System;
using System.ComponentModel;
using System.Data;
using System.Text;
using System.Windows.Forms;
using GenericTools;
using Excel = Microsoft.Office.Interop.Excel;
using Telerik.WinControls.UI;
using ReportingManagement.Components;
using System.Web.Services.Protocols;
using System.Collections.ObjectModel;
using ReportingManagement.Components.AutoReminder;
using DataModels.Enumerations;
using DataModels.Common;
using System.Windows.Interop;
using GenericTools.OfflineDataCapture;
using ReportingManagement.Components.Queries;
using ReportingManagement.Components.DHIS;
using System.Drawing;

namespace ReportingManagement
{
    public partial class MainWindow : Form, IQueryDesigner
    {
        #region Class Variables
        private UserInformation authenticatedUser;
        private int language;
        private bool m_LoggedOff = false;
        #endregion

        #region Class Constant
        private const int ENGLISH = 1;
        private const int KISWAHILI = 2;
        private const int DEFAULT_LANGUAGE = ENGLISH;
        #endregion

        #region Constructors
        public MainWindow(UserInformation authenticatedUser)
        {
            InitializeComponent();
            this.authenticatedUser = authenticatedUser;
            
            this.lblUser.Text = String.Format("Welcome {0}!", this.authenticatedUser.FullName);
            this.welcomeAccountToolStripMenuItem.Text = String.Format("&Welcome {0}!", this.authenticatedUser.FullName);
            
            this.language = DEFAULT_LANGUAGE;
            DataTable dataTable = null;

            switch (this.authenticatedUser.Level)
            {
                case AccessLevel.FACILITY:
                    this.tabReporting.TabPages.Remove(tabPageCustomReports);

                    this.tabMain.TabPages.Remove(tabPageSMSReminder);
                    this.tabMain.TabPages.Remove(tabPageTranslations);
                    this.tabMain.TabPages.Remove(tabPageAssistanceAssignment);
                    this.tabMain.TabPages.Remove(tabPageBlockedReports);
                    this.tabMain.TabPages.Remove(tabPageReportManagement);
                    this.tabMain.TabPages.Remove(tabPageUserManagement);
                    this.tabReporting.TabPages.Remove(tabPagePromisReporting);
                    this.tabMain.TabPages.Remove(tabPageQueries);
                    //tabPageDataCapture_Enter(null, null);   //initial load of data capture page
                    if ((AppConfiguration.AccessMethod == DataAccessMethod.OFFLINE_DATA_ACCESS)
                        || (AppConfiguration.AccessMethod == DataAccessMethod.OFFLINE_DIRECT_ACCESS))
                    {
                        //this.tabMain.TabPages.Remove(tabPageDataCapture);
                    }

                    string facilityCode = this.authenticatedUser.AccessLevelValue;
                    dataTable = Utilities.GetFacilityDetails(facilityCode);
                    
                    // BUG: The following call will cause fatal error when called in the absence
                    // of MS SQL server database called IQSMS_CacheDB
                    try { Utilities.CreateAccessibleFacilities(dataTable); }
                    catch { }
                    break;

                case AccessLevel.DISTRICT:
                    this.tabMain.TabPages.Remove(tabPageTranslations);
                    this.tabMain.TabPages.Remove(tabPageAssistanceAssignment);
                    //this.tabMain.TabPages.Remove(tabPageBlockedReports);
                    this.tabMain.TabPages.Remove(tabPageReportManagement);
                    //this.tabMain.TabPages.Remove(tabPageUserManagement);
                    this.tabReporting.TabPages.Remove(tabPagePromisReporting);
                    this.tabMain.TabPages.Remove(tabPageQueries);
                    //tabPageSMSReminder_Enter(null, null);   //initial load of sms reminder
                    if ((AppConfiguration.AccessMethod == DataAccessMethod.OFFLINE_DATA_ACCESS)
                        || (AppConfiguration.AccessMethod == DataAccessMethod.OFFLINE_DIRECT_ACCESS))
                    {
                        //this.tabMain.TabPages.Remove(tabPageDataCapture);
                    }

                    int districtID = Int32.Parse(this.authenticatedUser.AccessLevelValue);
                    dataTable = Utilities.GetFacilitiesDetailsByDistrict(districtID);

                    // BUG: The following call will cause fatal error when called in the absence
                    // of MS SQL server database called IQSMS_CacheDB
                    try { Utilities.CreateAccessibleFacilities(dataTable); }
                    catch { }
                    break;

                case AccessLevel.REGION:
                    this.tabMain.TabPages.Remove(tabPageTranslations);
                    this.tabMain.TabPages.Remove(tabPageAssistanceAssignment);
                    //this.tabMain.TabPages.Remove(tabPageBlockedReports);
                    this.tabMain.TabPages.Remove(tabPageDataCapture);
                    //this.tabMain.TabPages.Remove(tabPageUserManagement);
                    this.tabMain.TabPages.Remove(tabPageReportManagement);
                    this.tabReporting.TabPages.Remove(tabPagePromisReporting);
                    this.tabMain.TabPages.Remove(tabPageQueries);
                    //tabPageSMSReminder_Enter(null, null);   //initial load of sms reminder

                    int regionID = Int32.Parse(this.authenticatedUser.AccessLevelValue);
                    dataTable = Utilities.GetFacilitiesDetailsByRegion(regionID, this.authenticatedUser.SupportingPartnerId);

                    // BUG: The following call will cause fatal error when called in the absence
                    // of MS SQL server database called IQSMS_CacheDB
                    try { Utilities.CreateAccessibleFacilities(dataTable); }
                    catch { }
                    break;

                case AccessLevel.NATION:
                    this.tabMain.TabPages.Remove(tabPageTranslations);
                    //this.tabMain.TabPages.Remove(tabPageAssistanceAssignment);
                    //this.tabMain.TabPages.Remove(tabPageBlockedReports);
                    //this.tabMain.TabPages.Remove(tabPageDataCapture); ---- This is high connected with CSSC
                    //this.tabMain.TabPages.Remove(tabPageUserManagement);
                    this.tabMain.TabPages.Remove(tabPageReportManagement);
                    this.tabMain.TabPages.Remove(tabPageQueries);
                    //tabPageSMSReminder_Enter(null, null);   //initial load of sms reminder

                    dataTable = Utilities.GetAllFacilitiesStatus(this.authenticatedUser.SupportingPartnerId);
                    
                    // BUG: The following call will cause fatal error when called in the absence
                    // of MS SQL server database called IQSMS_CacheDB
                    try { Utilities.CreateAccessibleFacilities(dataTable); }
                    catch { }
                    break;

                case AccessLevel.ADMINISTRATOR:
                    setOtherSystemsFacilityDetailsToolStripMenuItem.Enabled = true;
                    setAutomaticSMSReminderToolStripMenuItem.Enabled = true;
                    setDHIS2DatasetsToolStripMenuItem.Enabled = true;
                    //tabPageSMSReminder_Enter(null, null);   //initial load of sms reminder
                    if ((AppConfiguration.AccessMethod == DataAccessMethod.OFFLINE_DATA_ACCESS)
                        || (AppConfiguration.AccessMethod == DataAccessMethod.OFFLINE_DIRECT_ACCESS))
                    {
                        //this.tabMain.TabPages.Remove(tabPageDataCapture);
                    }

                    dataTable = Utilities.GetAllFacilitiesStatus();

                    // BUG: The following call will cause fatal error when called in the absence
                    // of MS SQL server database called IQSMS_CacheDB
                    try { Utilities.CreateAccessibleFacilities(dataTable); }
                    catch { }
                    break;

                case AccessLevel.RESTRICTED:
                    this.tabMain.TabPages.Remove(tabPageFacilityManagement);
                    this.tabMain.TabPages.Remove(tabPageSMSReminder);
                    this.tabMain.TabPages.Remove(tabPageTranslations);
                    this.tabMain.TabPages.Remove(tabPageAssistanceAssignment);
                    this.tabMain.TabPages.Remove(tabPageBlockedReports);
                    this.tabMain.TabPages.Remove(tabPageDataCapture);
                    this.tabMain.TabPages.Remove(tabPageReportManagement);
                    this.tabMain.TabPages.Remove(tabPageUserManagement);
                    this.tabMain.TabPages.Remove(tabPageQueries);
                    break;
            }
            //tabPageBasicReports_Enter(null, null);

            if ((AppConfiguration.AccessMethod == DataAccessMethod.OFFLINE_DATA_ACCESS)
                || (AppConfiguration.AccessMethod == DataAccessMethod.OFFLINE_DIRECT_ACCESS))
            {
                lblUser.Enabled = false;
                viewProfileToolStripMenuItem.Enabled = false;

                lklChangePassword.Visible = false;
                changePasswordToolStripMenuItem.Enabled = false;

                DateTime? cacheCreationDate = Utilities.GetOfflineDataDate();
                DateTime? cacheDBCutOffPoint = Utilities.GetOfflineDataCutOffPoint();
                string databaseName = null;
                switch (AppConfiguration.AccessMethod)
                {
                    case DataAccessMethod.OFFLINE_DATA_ACCESS:
                        databaseName = "Microsoft Access";
                        break;

                    case DataAccessMethod.OFFLINE_DIRECT_ACCESS:
                        databaseName = "Microsoft SQL Server";
                        break;
                }

                if (cacheDBCutOffPoint.HasValue)
                {
                    TimeSpan timeSpan = DateTime.Now - cacheDBCutOffPoint.Value;
                    int months = (int)(timeSpan.TotalDays / 30);

                    string title = String.Format("{0} - Offline Mode using {1} [Last updated on {2} (Starting from {3} months ago)]",
                        this.Text, databaseName, cacheCreationDate.Value.ToLongDateString(), months);
                    this.Text = title;
                }
                else
                {
                    string title = String.Format("{0} - Offline Mode using {1} [Last updated on {2}]",
                        this.Text, databaseName, cacheCreationDate.Value.ToLongDateString());
                    this.Text = title;
                }
                tabPageBasicReports_Enter(null, null);

                btnRunOnRemoteServer.Enabled = false;
                elementHost2.Enabled = false;
            }

            if (AppConfiguration.AccessMethod == DataAccessMethod.DIRECT_ACCESS)
            {
                string databaseName = "Microsoft SQL Server";
                string title = String.Format("{0} - Online Mode using {1} [Direct Access to datasource]", this.Text, databaseName);
                this.Text = title;
            }

            if (AppConfiguration.IsRunningDemo) this.Text = this.Text + " :: Running DEMO";

            // Subscribing to offline data notification
            OfflineDataCapturing.OfflineDataChanged += OfflineDataCapturing_OfflineDataChanged;
        }

        void OfflineDataCapturing_OfflineDataChanged(object sender, GenericTools.OfflineDataCapture.OfflineDataCaptureArgs e)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke((MethodInvoker)delegate
                {
                    OfflineDataCapturing_OfflineDataChanged(sender, e);
                });
                return;
            }

            if (!offlineDataUploadingTimer.Enabled) offlineDataUploadingTimer.Start();
        }
        #endregion

        [System.Runtime.InteropServices.DllImport("user32.dll")]
        static public extern IntPtr GetActiveWindow();

        private void lklChangePassword_Click(object sender, EventArgs e)
        {
            ChangePassword changePassword = new ChangePassword(this.authenticatedUser);
            changePassword.ShowDialog(this);
        }

        private void DisplayErrorMessage(Exception ex)
        {
            Cursor.Current = Cursors.Default;
            toolStripStatusLabel.Text = "Error occured";
            string subTitle = String.Empty;
            string message = String.Empty;

            var invalidOperationExpection = ex as InvalidOperationException;
            if (invalidOperationExpection != null)
            {
                int index = invalidOperationExpection.Message.IndexOf("<!DOCTYPE");
                if (index != -1)
                {
                    string contentsToDisplay = invalidOperationExpection.Message.Substring(index);
                    var webBasedErrorDisplay = new WebBasedErrorDisplay(contentsToDisplay);
                    
                    WindowInteropHelper helper = new WindowInteropHelper(webBasedErrorDisplay);
                    helper.Owner = this.Handle;
                    webBasedErrorDisplay.ShowDialog();
                    return;
                }
            }

            var soapException = ex as SoapException;
            if (soapException != null)
            {
                subTitle = "Error in XML Web service method";
                message = String.Format("{0}\n\nError Details:\n{1}", subTitle, ex.Message);
                MessageBox.Show(this, message, AppConfiguration.ApplicationName,
                    MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }
            
            if ((AppConfiguration.AccessMethod == DataAccessMethod.OFFLINE_DATA_ACCESS) ||
                (AppConfiguration.AccessMethod == DataAccessMethod.OFFLINE_DIRECT_ACCESS))
            {
                subTitle = "Error occured during processing your request";
            }
            else 
            {
                subTitle = "Please make sure you have internet connection";
            }

            message = String.Format("{0}\n\nError Details:\n{1}", subTitle, ex.Message);
            MessageBox.Show(this, message, AppConfiguration.ApplicationName,
                MessageBoxButtons.OK, MessageBoxIcon.Stop);
        }

        /// <summary>
        /// This will try to update the toolstrip status label of the main as the 
        /// embeded user control changes its status.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ToolStripStatusLabel_StatusChanged(object sender, InteroperableUserControlEventArgs e)
        {
            if (e.Type == InteroperableUserControlEventArgs.StatusType.Text ||
                e.Type == InteroperableUserControlEventArgs.StatusType.ProgressAndText)
            {
                toolStripStatusLabel.Text = e.StatusText;
            }
        }

        private void lblUser_Click(object sender, EventArgs e)
        {
            try
            {
                UserDetails userDetails = new UserDetails(this.authenticatedUser, this.authenticatedUser);
                DialogResult response = userDetails.ShowDialog(this);
                if (response == System.Windows.Forms.DialogResult.OK)
                {
                    this.lblUser.Text = String.Format("Welcome {0}!", this.authenticatedUser.FullName);
                    this.welcomeAccountToolStripMenuItem.Text = String.Format("&Welcome {0}!", this.authenticatedUser.FullName);
                }
            }
            catch (Exception ex)
            {
                DisplayErrorMessage(ex);
            }
        }

        private void lklLogout_Click(object sender, EventArgs e)
        {
            this.Close();
            this.m_LoggedOff = true;
        }

        public bool LoggedOff
        {
            get
            {
                return this.m_LoggedOff;
            }
        }

        private void lklHelp_Click(object sender, EventArgs e)
        {
            try
            {
                string helpFile = String.Format(@"{0}\Resources\User Manual.chm", Application.StartupPath);
                System.Diagnostics.Process.Start(helpFile);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this,
                    String.Format("Could not open user guide.\n\n{0}", ex.Message),
                    "Error Opening Help", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void lklAbout_Click(object sender, EventArgs e)
        {
            AboutIQSMS aboutIQSMS = new AboutIQSMS();
            aboutIQSMS.ShowDialog(this);
        }

        //private void btnGeneratePMTCTMonthlyReport_Click(object sender, EventArgs e)
        //{
        //    btnGeneratePMTCTMonthlyReport.Enabled = false;
        //    tabMain.Enabled = false;
        //    Cursor.Current = Cursors.WaitCursor;
        //    toolStripStatusLabel.Text = "Determining output file";
        //    Application.DoEvents();
 
        //    const int TEMPLATE_ID = 2;
        //    ExcelTemplateReport excelReport = new ExcelTemplateReport(TEMPLATE_ID);
        //    string templatePath = String.Format(@"{0}\Resources\{1}", 
        //        Application.StartupPath, 
        //        excelReport.Filename);
        //    string excelTemplateSheetName = excelReport.Sheets[0].TemplateSheetName;

        //    string existingFilter = saveFileDialog.Filter;
        //    saveFileDialog.Filter = "Excel Workbook|*.xlsx";
        //    DialogResult response = saveFileDialog.ShowDialog(this);
        //    saveFileDialog.Filter = existingFilter;

        //    if (response == System.Windows.Forms.DialogResult.OK)
        //    {
        //        string selectedFilePath = saveFileDialog.FileName;

        //        Excel.Application excelApplication = null;
        //        Excel.Workbook excelWorkbook = null;
        //        Excel.Worksheet excelWorkSheet = null;
        //        Excel.Worksheet masterExcelWorkSheet = null;
        //        object misValue = System.Reflection.Missing.Value;
        //        try
        //        {
        //            System.IO.File.Delete(selectedFilePath);
        //            System.IO.File.Copy(templatePath, selectedFilePath);

        //            excelApplication = new Excel.Application();
        //            excelWorkbook = excelApplication.Workbooks.Open(selectedFilePath, 0, false, 5,
        //                "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);

        //            int currentSheetIndex = 1;
        //            masterExcelWorkSheet = (Excel.Worksheet)excelWorkbook.Worksheets.get_Item(currentSheetIndex);     // 1-based index

        //            int startYear = Int32.Parse(cboStartYear.Text);
        //            int startPeriod = Int32.Parse(cboStartPeriod.Text);
        //            int endYear = Int32.Parse(cboEndYear.Text);
        //            int endPeriod = Int32.Parse(cboEndPeriod.Text);

        //            // Get all facilities in particular district, district or nation   
        //            toolStripStatusLabel.Text = "Retrieving list of facilities...";
        //            Application.DoEvents();
        //            DataTable facilitiesDetails = null;
        //            if (rdoDistrict.Checked)
        //            {
        //                int districtID = Int32.Parse(cboAggregation.SelectedValue.ToString());
        //                facilitiesDetails = Utilities.GetFacilitiesDetailsByDistrict(districtID, true);
        //            }

        //            if (rdoRegion.Checked)
        //            {
        //                int regionID = Int32.Parse(cboAggregation.SelectedValue.ToString());
        //                facilitiesDetails = Utilities.GetFacilitiesDetailsByRegion(regionID, true);
        //            }

        //            if (rdoNation.Checked)
        //            {
        //                facilitiesDetails = Utilities.GetAllFacilitiesDetails(true, true);
        //            }
        //            toolStripStatusLabel.Text = String.Format("Found {0} facilities",
        //                facilitiesDetails.Rows.Count);
        //            Application.DoEvents();

        //            // Retrieving the complete dataset
        //            Dictionary<string, List<DataSet>> facilitiesDataset = GeneratePMTCTMonthlyReport(
        //                startYear, startPeriod, endYear, endPeriod, facilitiesDetails);

        //            string labelTamplate = "Writing to Excel: Sheet {0} [{1} of {2}]: {3} [{4} of {5}]";
        //            Excel.Worksheet lastWorkSheet = masterExcelWorkSheet;
        //            int sheetCount = 0;
        //            foreach (string month in facilitiesDataset.Keys)
        //            {
        //                sheetCount++;
        //                // Create a sheet from master template.
        //                masterExcelWorkSheet.Copy(misValue, lastWorkSheet);
        //                currentSheetIndex++;
        //                excelWorkSheet = (Excel.Worksheet)excelWorkbook.Worksheets.get_Item(currentSheetIndex);

        //                List<DataSet> facilitiesMonthData = facilitiesDataset[month];
        //                Excel.Range range = null;
        //                int facilityCount = facilitiesMonthData.Count;
        //                int columnOffset = 0;
        //                int rowOffset = 0;
        //                int rowIndex = 2;

        //                // Putting sheet name
        //                string[] components = month.Split('|');
        //                int iMonth = Int32.Parse(components[0]);
        //                int iYear = Int32.Parse(components[1]);
        //                string monthText = Utilities.GetMonthText(iMonth, true);
        //                string sheetLabel = String.Format("{0} {1}", monthText, iYear);
        //                excelWorkSheet.Name = sheetLabel;

        //                // Deteriming the district name
        //                DataTable dataTable = facilitiesMonthData[0].Tables[ExcelTemplateReport.FACILITY_INFO_TABLE];
        //                DataRow row = dataTable.Rows[0];
        //                string previousDistrict = row["DISTRICTNAME"].ToString();

        //                int firstColumnIndex = 2;
        //                int lastColumnIndex = firstColumnIndex;
        //                int facilityIndex = 0;

        //                foreach (DataSet facilityData in facilitiesMonthData)
        //                {
        //                    dataTable = facilityData.Tables[ExcelTemplateReport.FACILITY_INFO_TABLE];
        //                    row = dataTable.Rows[0];
        //                    string district = row["DISTRICTNAME"].ToString();
        //                    string facilityName = row["FACILITYNAME"].ToString();
        //                    facilityIndex++;
        //                    toolStripStatusLabel.Text = String.Format(labelTamplate, sheetLabel,
        //                        sheetCount, facilitiesDataset.Keys.Count, facilityName,
        //                        facilityIndex, facilityCount);
        //                    Application.DoEvents();

        //                    // Writing facility column in the sheet.
        //                    WriteFacilitiesInExcelSheet(excelWorkSheet, excelReport,
        //                        facilityData, excelTemplateSheetName, facilityCount, columnOffset, rowOffset);

        //                    if (previousDistrict != district)
        //                    {
        //                        rowIndex = 2;
        //                        //columnIndex = 2 + columnOffset - 1;
        //                        excelWorkSheet.Cells[rowIndex, firstColumnIndex] = previousDistrict;
        //                        range = excelWorkSheet.Range[
        //                            excelWorkSheet.Cells[rowIndex, firstColumnIndex],
        //                            excelWorkSheet.Cells[rowIndex, lastColumnIndex - 1]
        //                            ];
        //                        range.Merge(misValue);

        //                        range = excelWorkSheet.Range[
        //                            excelWorkSheet.Cells[rowIndex, firstColumnIndex],
        //                            excelWorkSheet.Cells[74, firstColumnIndex]
        //                            ];
        //                        range.Borders[Excel.XlBordersIndex.xlEdgeLeft].Weight = Excel.XlBorderWeight.xlMedium;

        //                        previousDistrict = district;
        //                        firstColumnIndex = lastColumnIndex;
        //                        lastColumnIndex = firstColumnIndex + 1;
        //                    }
        //                    else lastColumnIndex++;
        //                    columnOffset++;
        //                }
        //                //excelWorkbook.Save();

        //                // Writing name of the last district 
        //                excelWorkSheet.Cells[rowIndex, firstColumnIndex] = previousDistrict;
        //                range = excelWorkSheet.Range[
        //                    excelWorkSheet.Cells[rowIndex, firstColumnIndex],
        //                    excelWorkSheet.Cells[rowIndex, lastColumnIndex - 1]
        //                    ];
        //                range.Merge(misValue);

        //                range = excelWorkSheet.Range[
        //                            excelWorkSheet.Cells[rowIndex, firstColumnIndex],
        //                            excelWorkSheet.Cells[74, lastColumnIndex - 1]
        //                            ];
        //                range.Borders[Excel.XlBordersIndex.xlEdgeLeft].Weight = Excel.XlBorderWeight.xlMedium;

        //                lastWorkSheet = excelWorkSheet;
        //                toolStripStatusLabel.Text = "Saving workbook...";
        //                Application.DoEvents();
        //                excelWorkbook.Save();
        //            }

        //            toolStripStatusLabel.Text = "Closing Excel...";
        //            Application.DoEvents();
        //            // Delete the template
        //            excelApplication.DisplayAlerts = false;
        //            masterExcelWorkSheet.Delete();
        //            excelWorkbook.Save();

        //            excelWorkbook.Close(true, misValue, misValue);
        //            excelApplication.Quit();

        //            ReleaseObject(excelWorkSheet);
        //            ReleaseObject(excelWorkbook);
        //            ReleaseObject(excelApplication);

        //            toolStripStatusLabel.Text = "Ready";
        //            Application.DoEvents();

        //            if (System.IO.File.Exists(selectedFilePath))
        //            {
        //                response = MessageBox.Show(
        //                String.Format("Report has been generated successfully. It has been saved in {0}.\n\nDo you want to open it?",
        //                    selectedFilePath), AppConfiguration.ApplicationName, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
        //                if (response == System.Windows.Forms.DialogResult.Yes) System.Diagnostics.Process.Start(selectedFilePath);
        //            }
        //            else
        //            {
        //                MessageBox.Show("Operation did not complete successfully", 
        //                    AppConfiguration.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
        //            }
                    
        //        }
        //        catch (Exception ex)
        //        {
        //            MessageBox.Show(ex.Message, AppConfiguration.ApplicationName,
        //                MessageBoxButtons.OK, MessageBoxIcon.Error);
        //            try
        //            {
        //                excelWorkbook.Close(true, misValue, misValue);
        //            }
        //            catch { }
        //            try
        //            {
        //                excelApplication.Quit();
        //            }
        //            catch { }

        //            ReleaseObject(excelWorkSheet);
        //            ReleaseObject(excelWorkbook);
        //            ReleaseObject(excelApplication);
        //            toolStripStatusLabel.Text = "Error Occured while generating report";
        //        }
        //    }
        //    else
        //    {
        //        toolStripStatusLabel.Text = "Ready";
        //    }
        //    btnGeneratePMTCTMonthlyReport.Enabled = true;
        //    tabMain.Enabled = true;
        //    Cursor.Current = Cursors.Default;
        //}

        //private void btnGenerateSAPR1_Click(object sender, EventArgs e)
        //{
        //    tabMain.Enabled = false;
        //    Application.DoEvents();

        //    Cursor.Current = Cursors.WaitCursor;
        //    toolStripStatusLabel.Text = "Determining output file";
        //    Application.DoEvents();

        //    const int TEMPLATE_ID = 1;
        //    ExcelTemplateReport report = new ExcelTemplateReport(TEMPLATE_ID);
        //    string templatePath = String.Format(@"{0}\Resources\{1}", 
        //        Application.StartupPath, 
        //        report.Filename);

        //    string existingFilter = saveFileDialog.Filter;
        //    saveFileDialog.Filter = "Excel 97 - 2003 Workbook|*.xls";
        //    DialogResult response = saveFileDialog.ShowDialog(this);
        //    saveFileDialog.Filter = existingFilter;

        //    if (response == System.Windows.Forms.DialogResult.OK)
        //    {
        //        string selectedFilePath = saveFileDialog.FileName;

        //        Excel.Application excelApplication = null;
        //        Excel.Workbook excelWorkbook = null;
        //        Excel.Worksheet excelWorkSheet = null;
        //        object misValue = System.Reflection.Missing.Value;
        //        try
        //        {
        //            System.IO.File.Delete(selectedFilePath);
        //            System.IO.File.Copy(templatePath, selectedFilePath);

        //            excelApplication = new Excel.Application();
        //            excelWorkbook = excelApplication.Workbooks.Open(selectedFilePath, 0, false, 5,
        //                "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);

        //            int currentSheetIndex = 1;
        //            excelWorkSheet = (Excel.Worksheet)excelWorkbook.Worksheets.get_Item(currentSheetIndex);     // 1-based index

        //            int startYear = Int32.Parse(cboStartYear.Text);
        //            int startPeriod = Int32.Parse(cboStartPeriod.Text);
        //            int endYear = Int32.Parse(cboEndYear.Text);
        //            int endPeriod = Int32.Parse(cboEndPeriod.Text);

        //            const string SUMMARY_SHEET = "Summary";
        //            const string DATA_SHEET = "Data";

        //            const int ANC_REPORT_ID = 6;
        //            const int PCR_REPORT_ID = 8;
        //            const int MAT_REPORT_ID = 7;
        //            const int MC_REPORT_ID = 9;

        //            // Get all facilities in particular district, district or nation   
        //            DataTable facilitiesDetails = null;
        //            DataSet summaryDataSet = new DataSet();

        //            toolStripStatusLabel.Text = "Retrieving records from database. Please wait...";
        //            Application.DoEvents();

        //            if (rdoDistrict.Checked)
        //            {
        //                int districtID = Int32.Parse(cboAggregation.SelectedValue.ToString());
        //                toolStripStatusLabel.Text = "Retrieving list of facilities. Please wait...";
        //                Application.DoEvents();
        //                facilitiesDetails = Utilities.GetFacilitiesDetailsByDistrict(districtID, true);

        //                toolStripStatusLabel.Text = "Retrieving facilities ANC reports. Please wait...";
        //                Application.DoEvents();
        //                DataTable summaryData = Utilities.GetDistrictReport(districtID,
        //                    ANC_REPORT_ID, startYear, startPeriod, endYear, endPeriod, true);
        //                summaryData.TableName = ExcelTemplateReport.ANC_TABLE;
        //                summaryDataSet.Tables.Add(summaryData);

        //                toolStripStatusLabel.Text = "Retrieving facilities PCR reports. Please wait...";
        //                Application.DoEvents();
        //                summaryData = Utilities.GetDistrictReport(districtID, PCR_REPORT_ID,
        //                    startYear, startPeriod, endYear, endPeriod, true);
        //                summaryData.TableName = ExcelTemplateReport.PCR_TABLE;
        //                summaryDataSet.Tables.Add(summaryData);

        //                toolStripStatusLabel.Text = "Retrieving facilities MAT reports. Please wait...";
        //                Application.DoEvents();
        //                summaryData = Utilities.GetDistrictReport(districtID, MAT_REPORT_ID,
        //                    startYear, startPeriod, endYear, endPeriod, true);
        //                summaryData.TableName = ExcelTemplateReport.MAT_TABLE;
        //                summaryDataSet.Tables.Add(summaryData);

        //                toolStripStatusLabel.Text = "Retrieving facilities MC reports. Please wait...";
        //                Application.DoEvents();
        //                summaryData = Utilities.GetDistrictReport(districtID, MC_REPORT_ID,
        //                    startYear, startPeriod, endYear, endPeriod, true);
        //                summaryData.TableName = ExcelTemplateReport.MC_TABLE;
        //                summaryDataSet.Tables.Add(summaryData);
        //            }

        //            if (rdoRegion.Checked)
        //            {
        //                int regionID = Int32.Parse(cboAggregation.SelectedValue.ToString());
        //                toolStripStatusLabel.Text = "Retrieving list of facilities. Please wait...";
        //                Application.DoEvents();
        //                facilitiesDetails = Utilities.GetFacilitiesDetailsByRegion(regionID, true);

        //                toolStripStatusLabel.Text = "Retrieving facilities ANC reports. Please wait...";
        //                Application.DoEvents();
        //                DataTable summaryData = Utilities.GetRegionReport(regionID,
        //                    ANC_REPORT_ID, startYear, startPeriod, endYear, endPeriod, true);
        //                summaryData.TableName = ExcelTemplateReport.ANC_TABLE;
        //                summaryDataSet.Tables.Add(summaryData);

        //                toolStripStatusLabel.Text = "Retrieving facilities PCR reports. Please wait...";
        //                Application.DoEvents();
        //                summaryData = Utilities.GetRegionReport(regionID, PCR_REPORT_ID,
        //                    startYear, startPeriod, endYear, endPeriod, true);
        //                summaryData.TableName = ExcelTemplateReport.PCR_TABLE;
        //                summaryDataSet.Tables.Add(summaryData);

        //                toolStripStatusLabel.Text = "Retrieving facilities MAT reports. Please wait...";
        //                Application.DoEvents();
        //                summaryData = Utilities.GetRegionReport(regionID, MAT_REPORT_ID,
        //                    startYear, startPeriod, endYear, endPeriod, true);
        //                summaryData.TableName = ExcelTemplateReport.MAT_TABLE;
        //                summaryDataSet.Tables.Add(summaryData);

        //                toolStripStatusLabel.Text = "Retrieving facilities MC reports. Please wait...";
        //                Application.DoEvents();
        //                summaryData = Utilities.GetRegionReport(regionID, MC_REPORT_ID,
        //                    startYear, startPeriod, endYear, endPeriod, true);
        //                summaryData.TableName = ExcelTemplateReport.MC_TABLE;
        //                summaryDataSet.Tables.Add(summaryData);
        //            }

        //            if (rdoNation.Checked)
        //            {
        //                toolStripStatusLabel.Text = "Retrieving list of facilities. Please wait...";
        //                Application.DoEvents();
        //                facilitiesDetails = Utilities.GetAllFacilitiesDetails(true, true);

        //                toolStripStatusLabel.Text = "Retrieving facilities ANC reports. Please wait...";
        //                Application.DoEvents();
        //                DataTable summaryData = Utilities.GetNationReport(
        //                    ANC_REPORT_ID, startYear, startPeriod, endYear, endPeriod, true);
        //                summaryData.TableName = ExcelTemplateReport.ANC_TABLE;
        //                summaryDataSet.Tables.Add(summaryData);

        //                toolStripStatusLabel.Text = "Retrieving facilities PCR reports. Please wait...";
        //                Application.DoEvents();
        //                summaryData = Utilities.GetNationReport(PCR_REPORT_ID,
        //                    startYear, startPeriod, endYear, endPeriod, true);
        //                summaryData.TableName = ExcelTemplateReport.PCR_TABLE;
        //                summaryDataSet.Tables.Add(summaryData);

        //                toolStripStatusLabel.Text = "Retrieving facilities MAT reports. Please wait...";
        //                Application.DoEvents();
        //                summaryData = Utilities.GetNationReport(MAT_REPORT_ID,
        //                    startYear, startPeriod, endYear, endPeriod, true);
        //                summaryData.TableName = ExcelTemplateReport.MAT_TABLE;
        //                summaryDataSet.Tables.Add(summaryData);

        //                toolStripStatusLabel.Text = "Retrieving facilities MC reports. Please wait...";
        //                Application.DoEvents();
        //                summaryData = Utilities.GetNationReport(MC_REPORT_ID,
        //                    startYear, startPeriod, endYear, endPeriod, true);
        //                summaryData.TableName = ExcelTemplateReport.MC_TABLE;
        //                summaryDataSet.Tables.Add(summaryData);
        //            }

        //            toolStripStatusLabel.Text = "Writing to Excel sheet summary data. Please wait...";
        //            Application.DoEvents();
        //            report.DataSource = summaryDataSet;
        //            report.WriteDataToExcelSheet(excelWorkSheet, SUMMARY_SHEET, 0, 0);
        //            excelWorkbook.Save();

        //            int facilityCount = facilitiesDetails.Rows.Count;
        //            int facilityIndex = 0;
        //            string template = "{0} in {1} | {2} ({3} of {4}): Loading {5} report data, please wait...";
        //            List<DataSet> facilitiesDataSet = new List<DataSet>();
        //            foreach (DataRow row in facilitiesDetails.Rows)
        //            {
        //                facilityIndex++;
        //                string facilityCode = row["FacCode"].ToString();
        //                string facilityName = row["FacName"].ToString();
        //                string districtName = row["District"].ToString();
        //                string regionName = row["RegionName"].ToString();

        //                toolStripStatusLabel.Text = String.Format(template, districtName, regionName,
        //                    facilityName, facilityIndex, facilityCount, "ANC");
        //                Application.DoEvents();
        //                DataSet facilityDataset = new DataSet();
        //                DataTable data = Utilities.GetFacilityReport(facilityCode,
        //                    ANC_REPORT_ID, startYear, startPeriod, endYear, endPeriod, true);
        //                data.TableName = ExcelTemplateReport.ANC_TABLE;
        //                facilityDataset.Tables.Add(data);

        //                toolStripStatusLabel.Text = String.Format(template, districtName, regionName,
        //                    facilityName, facilityIndex, facilityCount, "PCR");
        //                Application.DoEvents();
        //                data = Utilities.GetFacilityReport(facilityCode,
        //                    PCR_REPORT_ID, startYear, endPeriod, endYear, endPeriod, true);
        //                data.TableName = ExcelTemplateReport.PCR_TABLE;
        //                facilityDataset.Tables.Add(data);

        //                toolStripStatusLabel.Text = String.Format(template, districtName, regionName,
        //                    facilityName, facilityIndex, facilityCount, "MAT");
        //                Application.DoEvents();
        //                data = Utilities.GetFacilityReport(facilityCode, MAT_REPORT_ID,
        //                    startYear, startPeriod, endYear, endPeriod, true);
        //                data.TableName = ExcelTemplateReport.MAT_TABLE;
        //                facilityDataset.Tables.Add(data);

        //                toolStripStatusLabel.Text = String.Format(template, districtName, regionName,
        //                    facilityName, facilityIndex, facilityCount, "MC");
        //                Application.DoEvents();
        //                data = Utilities.GetFacilityReport(facilityCode, MC_REPORT_ID,
        //                    startYear, startPeriod, endYear, endPeriod, true);
        //                data.TableName = ExcelTemplateReport.MC_TABLE;
        //                facilityDataset.Tables.Add(data);

        //                DataTable facilityInfo = new DataTable();
        //                DataColumn column = new DataColumn("FACCODE", Type.GetType("System.String"));
        //                facilityInfo.Columns.Add(column);
        //                column = new DataColumn("FACILITYNAME", Type.GetType("System.String"));
        //                facilityInfo.Columns.Add(column);
        //                column = new DataColumn("DISTRICTNAME", Type.GetType("System.String"));
        //                facilityInfo.Columns.Add(column);
        //                column = new DataColumn("REGIONNAME", Type.GetType("System.String"));
        //                facilityInfo.Columns.Add(column);
        //                string[] values = { facilityCode, facilityName, districtName, regionName };
        //                facilityInfo.Rows.Add(values);
        //                facilityInfo.TableName = ExcelTemplateReport.FACILITY_INFO_TABLE;
        //                facilityDataset.Tables.Add(facilityInfo);

        //                facilitiesDataSet.Add(facilityDataset);
        //            }

        //            excelWorkSheet = (Excel.Worksheet)excelWorkbook.Worksheets.get_Item(2);
        //            ExcelTemplateReport excelReport = new ExcelTemplateReport(TEMPLATE_ID);
        //            int columnOffset = 0;
        //            int rowOffset = 0;
        //            template = @"Writing to Facility data to Excel Sheet [{0} of {1}]";
        //            facilityIndex = 0;
        //            facilityCount = facilitiesDataSet.Count;
        //            foreach (DataSet facilityDataSet in facilitiesDataSet)
        //            {
        //                facilityIndex++;
        //                toolStripStatusLabel.Text = String.Format(template, facilityIndex, facilityCount);
        //                Application.DoEvents();

        //                // Writing facility column in the sheet.
        //                WriteFacilitiesInExcelSheet(excelWorkSheet, excelReport, facilityDataSet,
        //                    DATA_SHEET, facilityCount, columnOffset, rowOffset);
        //                rowOffset++;
        //                excelWorkbook.Save();
        //            }

        //            toolStripStatusLabel.Text = "Closing Excel and releasing resources. Please wait...";
        //            Application.DoEvents();
        //            excelWorkbook.Close(true, misValue, misValue);
        //            excelApplication.Quit();

        //            ReleaseObject(excelWorkSheet);
        //            ReleaseObject(excelWorkbook);
        //            ReleaseObject(excelApplication);

        //            toolStripStatusLabel.Text = "Ready";
        //            Application.DoEvents();

        //            if (System.IO.File.Exists(selectedFilePath))
        //            {
        //                response = MessageBox.Show(
        //                String.Format("Report has been generated successfully. It has been saved in {0}.\n\nDo you want to open it?",
        //                    selectedFilePath), AppConfiguration.ApplicationName, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
        //                if (response == System.Windows.Forms.DialogResult.Yes) System.Diagnostics.Process.Start(selectedFilePath);
        //            }
        //            else
        //            {
        //                MessageBox.Show("Operation did not complete successfully",
        //                    AppConfiguration.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
        //            }
        //        }
        //        catch (Exception ex)
        //        {
        //            MessageBox.Show(ex.Message, AppConfiguration.ApplicationName,
        //                MessageBoxButtons.OK, MessageBoxIcon.Error);
        //            try
        //            {
        //                excelWorkbook.Close(true, misValue, misValue);
        //            }
        //            catch { }
        //            try
        //            {
        //                excelApplication.Quit();
        //            }
        //            catch { }

        //            ReleaseObject(excelWorkSheet);
        //            ReleaseObject(excelWorkbook);
        //            ReleaseObject(excelApplication);

        //            toolStripStatusLabel.Text = "Error occured while trying to generate report";
        //            Application.DoEvents();
        //        }
        //    }
        //    else
        //    {
        //        toolStripStatusLabel.Text = "Ready";
        //    }

        //    tabMain.Enabled = true;
        //}

        private void ReleaseObject(object obj)
        {
            try
            {
                if (obj == null) return;
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
                MessageBox.Show(String.Format("Unable to release the Object {0}", ex.ToString()));
            }
            finally
            {
                GC.Collect();
            }
        }

        //private Dictionary<string, List<DataSet>> GeneratePMTCTMonthlyReport(int startYear, int startPeriod, 
        //    int endYear, int endPeriod, DataTable facilitiesDetails)
        //{
        //    Dictionary<string, List<DataSet>> facilitiesDataSet = new Dictionary<string, List<DataSet>>();
        //    // Retrieving each report, for each facility, for each month.           

        //    if (startYear == endYear)
        //    {
        //        FindDataSetByMonths(startYear, startPeriod, endPeriod, facilitiesDetails, facilitiesDataSet);
        //    }
        //    else
        //    {
        //        int currentYear = startYear;
        //        do
        //        {
        //            int startingPeriod = 1;
        //            int endingPeriod = 12;
        //            if (currentYear == startYear) startingPeriod = startPeriod;
        //            if (currentYear == endYear) endingPeriod = endPeriod;

        //            FindDataSetByMonths(currentYear, startingPeriod, endingPeriod, facilitiesDetails, facilitiesDataSet);
        //            currentYear++;
        //        } while (currentYear <= endYear);
        //    }
        //    return facilitiesDataSet;
        //}

        //private Dictionary<string, List<DataSet>> GenerateAPRReportDataSet(int startYear, int startPeriod,
        //    int endYear, int endPeriod, DataTable facilitiesDetails)
        //{
        //    Dictionary<string, List<DataSet>> facilitiesDataSet = new Dictionary<string, List<DataSet>>();
        //    // Retrieving each report, for each facility, for each month.           

        //    if (startYear == endYear)
        //    {
        //        FindDataSetByMonths(startYear, startPeriod, endPeriod, facilitiesDetails, facilitiesDataSet);
        //    }
        //    else
        //    {
        //        int currentYear = startYear;
        //        do
        //        {
        //            int startingPeriod = 1;
        //            int endingPeriod = 12;
        //            if (currentYear == startYear) startingPeriod = startPeriod;
        //            if (currentYear == endYear) endingPeriod = endPeriod;

        //            FindDataSetByMonths(currentYear, startingPeriod, endingPeriod, facilitiesDetails, facilitiesDataSet);
        //            currentYear++;
        //        } while (currentYear <= endYear);
        //    }
        //    return facilitiesDataSet;
        //}

        //private void FindDataSetByMonths(int year, int startPeriod, int endPeriod,
        //    DataTable facilitiesDetails, Dictionary<string, List<DataSet>> facilitiesMonthsDataSet)
        //{
        //    const int ANC_REPORT_ID = 6;
        //    const int PCR_REPORT_ID = 8;
        //    const int MAT_REPORT_ID = 7;
        //    const int MC_REPORT_ID = 9;

        //    // Going through each month independently
        //    for (int p = startPeriod; p <= endPeriod; p++)
        //    {
        //        string key = String.Format("{0}|{1}", p, year);
        //        List<DataSet> facilitiesMonthDataSet = new List<DataSet>();
        //        string template = "{0} in {1} | {2} ({3} of {4}): Loading data for {5} {6}";
        //        int index = 0;
        //        // Now for each month, find report of each facility presented.
        //        foreach (DataRow row in facilitiesDetails.Rows)
        //        {
        //            index++;
        //            string facilityCode = row["FacCode"].ToString();
        //            string facilityName = row["FacName"].ToString();
        //            string districtName = row["District"].ToString();
        //            string regionName = row["RegionName"].ToString();
        //            string monthText = Utilities.GetMonthText(p);
                    
        //            toolStripStatusLabel.Text = String.Format(template,
        //                districtName, regionName, facilityName, index, 
        //                facilitiesDetails.Rows.Count, monthText, year);
        //            Application.DoEvents();

        //            DataSet facilityMonthDataset = new DataSet();
        //            DataTable data = Utilities.GetFacilityReport(facilityCode, 
        //                ANC_REPORT_ID, year, p, year, p, true);
        //            data.TableName = ExcelTemplateReport.ANC_TABLE;
        //            facilityMonthDataset.Tables.Add(data);

        //            data = Utilities.GetFacilityReport(facilityCode, 
        //                PCR_REPORT_ID, year, p, year, p, true);
        //            data.TableName = ExcelTemplateReport.PCR_TABLE;
        //            facilityMonthDataset.Tables.Add(data);

        //            data = Utilities.GetFacilityReport(facilityCode, 
        //                MAT_REPORT_ID, year, p, year, p, true);
        //            data.TableName = ExcelTemplateReport.MAT_TABLE;
        //            facilityMonthDataset.Tables.Add(data);

        //            data = Utilities.GetFacilityReport(facilityCode, 
        //                MC_REPORT_ID, year, p, year, p, true);
        //            data.TableName = ExcelTemplateReport.MC_TABLE;
        //            facilityMonthDataset.Tables.Add(data);

        //            DataTable facilityInfo = new DataTable();
        //            DataColumn column = new DataColumn("FACCODE", Type.GetType("System.String"));
        //            facilityInfo.Columns.Add(column);
        //            column = new DataColumn("FACILITYNAME", Type.GetType("System.String"));
        //            facilityInfo.Columns.Add(column);
        //            column = new DataColumn("DISTRICTNAME", Type.GetType("System.String"));
        //            facilityInfo.Columns.Add(column);
        //            column = new DataColumn("REGIONNAME", Type.GetType("System.String"));
        //            facilityInfo.Columns.Add(column);
        //            string[] values = { facilityCode, facilityName, districtName, regionName };
        //            facilityInfo.Rows.Add(values);
        //            facilityInfo.TableName = ExcelTemplateReport.FACILITY_INFO_TABLE;
        //            facilityMonthDataset.Tables.Add(facilityInfo);

        //            facilitiesMonthDataSet.Add(facilityMonthDataset);
        //        }
        //        //facilitiesDataSet.Add(facilitiesMonthDataSet);
        //        facilitiesMonthsDataSet[key] = facilitiesMonthDataSet;
        //        //facilitiesDataSet.Add(facilitiesMonthDataSetD);
        //    }
        //}

        private void WriteFacilitiesInExcelSheet(Excel.Worksheet excelWorkSheet, 
            ExcelTemplateReport excelReport, DataSet dataset, 
            string templateSheetName, int facilityCount, int columnOffset, int rowOffset)
        {
            object misValue = System.Reflection.Missing.Value;
            excelReport.DataSource = dataset;
            excelReport.WriteDataToExcelSheet(excelWorkSheet, templateSheetName, columnOffset, rowOffset);

            foreach (ExcelTemplateSheet sheet in excelReport.Sheets)
            {
                if (sheet.TemplateSheetName == templateSheetName)
                {
                    if (sheet.HasRepetitiveRows)
                    {
                        if (facilityCount > (rowOffset + 3))
                        {
                            //Insert new row
                            int rowIndex = sheet.FirstRepetitiveRowCellIndex + rowOffset + 1;
                            Excel.Range range = (Excel.Range)excelWorkSheet.Rows[rowIndex, misValue];
                            range.Insert(misValue, Excel.XlInsertFormatOrigin.xlFormatFromLeftOrAbove);
                        }
                    }

                    if (sheet.HasRepetitveColumns)
                    {
                        if ((facilityCount > (columnOffset + 3)))
                        {
                            //Insert new column
                            int columnIndex = sheet.FirstRepetitiveColumnCellIndex + columnOffset + 1;
                            //Excel.Range range = excelWorkSheet.get_Range(
                            //    excelWorkSheet.Cells[1, columnIndex],
                            //    excelWorkSheet.Cells[excelWorkSheet.Rows.Count, columnIndex]);
                            Excel.Range range = excelWorkSheet.Range[
                                excelWorkSheet.Cells[1, columnIndex],
                                excelWorkSheet.Cells[excelWorkSheet.Rows.Count, columnIndex]
                                ];
                            range.Insert(misValue, Excel.XlInsertShiftDirection.xlShiftToRight);
                        }
                    }
                    break;
                }
            }
        }

        private void btnGenerateSAPR_Click(object sender, EventArgs e)
        {
            string existingFilter = saveFileDialog.Filter;
            saveFileDialog.Filter = "Excel 97 - 2003 Workbook|*.xls";
            DialogResult response = saveFileDialog.ShowDialog(this);
            saveFileDialog.Filter = existingFilter;

            if (response == System.Windows.Forms.DialogResult.OK)
            {
                m_SelectedFilePath = saveFileDialog.FileName;
                generatingSAPR = true;
                sapr_startYear = Int32.Parse(cboStartYear.Text);
                sapr_startPeriod = Int32.Parse(cboStartPeriod.Text);
                sapr_endYear = Int32.Parse(cboEndYear.Text);
                sapr_endPeriod = Int32.Parse(cboEndPeriod.Text);

                sapr_districtsSelected = rdoDistrict.Checked;
                sapr_regionsSelected = rdoRegion.Checked;
                sapr_nationSelected = rdoNation.Checked;

                sapr_districtID = sapr_regionID = Int32.Parse(cboAggregation.SelectedValue.ToString());

                groupBox8.Enabled = false;
                cboAggregation.Enabled = false;
                cboStartYear.Enabled = false;
                cboStartPeriod.Enabled = false;

                cboEndYear.Enabled = false;
                cboEndPeriod.Enabled = false;

                btnGenerateDonorReport.Enabled = false;
                btnGenerateSAPR.Enabled = false;
                btnGeneratePMTCTMonthlyReport.Enabled = false;
                btnGenerateSAPRPromise.Enabled = false;

                lblProgress.Visible = true;
                progressBar.Visible = true;
                btnCancel.Visible = true;

                if (backgroundWorker != null) backgroundWorker.Dispose();
                backgroundWorker = new BackgroundWorker();
                backgroundWorker.WorkerSupportsCancellation = true;
                backgroundWorker.WorkerReportsProgress = true;

                backgroundWorker.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork);
                backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker_ProgressChanged);
                backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker_RunWorkerCompleted);

                backgroundWorker.RunWorkerAsync();
            }
        }      

        private void CreateExcelExportFile(DataTable dataTable)
        {
            string previousFilter = saveFileDialog.Filter;
            saveFileDialog.Filter = "Excel Workbook|*.xlsx";
            DialogResult response = saveFileDialog.ShowDialog(this);
            saveFileDialog.Filter = previousFilter;
            if (response == System.Windows.Forms.DialogResult.OK)
            {
                //Excel.Application excelApplication = null;
                Excel._Application excelApplication = null;
                Excel.Workbooks excelWorkbooks = null;
                Excel.Workbook excelWorkbook = null;
                Excel.Sheets excelWorksheets = null;
                Excel.Worksheet excelWorksheet = null;

                try
                {
                    string filename = saveFileDialog.FileName;
                    object misValue = System.Reflection.Missing.Value;

                    //excelApplication = new Excel.ApplicationClass();
                    excelApplication = new Excel.Application();
                    excelWorkbooks = excelApplication.Workbooks;
                    excelWorkbook = excelWorkbooks.Add(misValue);
                    excelWorksheets = excelWorkbook.Worksheets;
                    excelWorksheet = (Excel.Worksheet)excelWorksheets.get_Item(1);

                    int rowOffset = 1;
                    int columnOffset = 1;
                    Utilities.WriteDataTableToExcelSheet(excelWorksheet, dataTable, rowOffset, columnOffset, true);

                    System.IO.File.Delete(filename);
                    excelWorkbook.SaveAs(filename, misValue, misValue,
                        misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive,
                        misValue, misValue, misValue, misValue, misValue);
                    excelWorkbook.Close(true, misValue, misValue);
                    excelApplication.Quit();

                    ReleaseObject(excelWorksheet);
                    ReleaseObject(excelWorksheets);
                    ReleaseObject(excelWorkbook);
                    ReleaseObject(excelWorkbooks);
                    ReleaseObject(excelApplication);

                    if (System.IO.File.Exists(filename))
                    {
                        response = MessageBox.Show(this,
                        String.Format("Data Export completed successfully. It has been saved in {0}" +
                            ".\n\nDo you want to open it?", filename),
                        AppConfiguration.ApplicationName,
                        MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        if (response == System.Windows.Forms.DialogResult.Yes)
                        {
                            try
                            {
                                System.Diagnostics.Process.Start(filename);
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(
                                    String.Format("Failed to open the file.{0}{0}Error details:{0}{1}",
                                        Environment.NewLine, ex.Message),
                                    AppConfiguration.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show("Operation did not complete successfully",
                            AppConfiguration.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }

                    
                    return;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, ex.Message, AppConfiguration.ApplicationName,
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                finally
                {
                    ReleaseObject(excelWorksheet);
                    ReleaseObject(excelWorksheets);
                    ReleaseObject(excelWorkbook);
                    ReleaseObject(excelWorkbooks);
                    ReleaseObject(excelApplication);
                }
            }
        }

        private void btnGenerateSAPRPromise_Click(object sender, EventArgs e)
        {
            //string existingFilter = saveFileDialog.Filter;
            //saveFileDialog.Filter = "Excel 97 - 2003 Workbook|*.xls";            
            //DialogResult response = saveFileDialog.ShowDialog(this);
            //saveFileDialog.Filter = existingFilter;
            if (!rdoNation.Checked)
            {
                MessageBox.Show(this, "This report is only generated at nation level!",
                    AppConfiguration.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
            folderBrowserDialog.ShowNewFolderButton = true;
            folderBrowserDialog.Description = "Select the folder for putting output files";
            DialogResult response = folderBrowserDialog.ShowDialog(this);

            if (response == System.Windows.Forms.DialogResult.OK)
            {
                //m_SelectedFilePath = saveFileDialog.FileName;
                m_SelectedFilePath = folderBrowserDialog.SelectedPath;
                generatingSAPRPromise = true;
                sapr_startYear = Int32.Parse(cboStartYear.Text);
                sapr_startPeriod = Int32.Parse(cboStartPeriod.Text);
                sapr_endYear = Int32.Parse(cboEndYear.Text);
                sapr_endPeriod = Int32.Parse(cboEndPeriod.Text);

                sapr_districtsSelected = rdoDistrict.Checked;
                sapr_regionsSelected = rdoRegion.Checked;
                sapr_nationSelected = rdoNation.Checked;

                sapr_districtID = sapr_regionID = Int32.Parse(cboAggregation.SelectedValue.ToString());

                response = MessageBox.Show(this, "Do you want to use previous report as the baseline for generating this one?",
                    AppConfiguration.ApplicationName, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (response == System.Windows.Forms.DialogResult.Yes)
                {
                    sapr_useBaselineData = true;
                    response = MessageBox.Show(this, "Do you want to use the maximum value between SAPR + 6 months and 12 months?",
                        AppConfiguration.ApplicationName, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (response == System.Windows.Forms.DialogResult.Yes)
                    {
                        sapr_useMaximumValues = true;
                        sapr_useMax_startDate = DateTime.Parse("2012-09-30");
                        sapr_useMax_endDate = DateTime.Parse("2013-09-30");
                    }
                    else sapr_useMaximumValues = false;
                }
                else sapr_useBaselineData = false;

                groupBox8.Enabled = false;
                cboAggregation.Enabled = false;
                cboStartYear.Enabled = false;
                cboStartPeriod.Enabled = false;

                cboEndYear.Enabled = false;
                cboEndPeriod.Enabled = false;

                btnGenerateDonorReport.Enabled = false;
                btnGenerateSAPR.Enabled = false;
                btnGeneratePMTCTMonthlyReport.Enabled = false;
                btnGenerateSAPRPromise.Enabled = false;

                lblProgress.Visible = true;
                progressBar.Visible = true;
                btnCancel.Visible = true;

                if (backgroundWorker != null) backgroundWorker.Dispose();
                backgroundWorker = new BackgroundWorker();
                backgroundWorker.WorkerSupportsCancellation = true;
                backgroundWorker.WorkerReportsProgress = true;

                backgroundWorker.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork);
                backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker_ProgressChanged);
                backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker_RunWorkerCompleted);

                backgroundWorker.RunWorkerAsync();
            }
        }

        private void btnSaveQuery_Click(object sender, EventArgs e)
        {
            sqlTextEditorSaveQuery.Text = sqlTextEditor.Text;
            tabQueries.SelectedTab = tabPageQueriesSaveQuery;
        }

        private void btnCancelQuerySave_Click(object sender, EventArgs e)
        {
            tabQueries.SelectedTab = tabPageQueriesDesign;
        }

        private void tabPage4_Enter(object sender, EventArgs e)
        {
            sqlTextEditorSaveQuery.Text = sqlTextEditor.Text;
        }

        // Query Output Tab
        private ObservableCollection<Models.QueryCategory> _QueryCategories = null;


        private void tabPageDetails_Enter(object sender, EventArgs e)
        {
            dgvRepDetails.Refresh();
        }

        private void tabPageSubmittedReports_Enter(object sender, EventArgs e)
        {
            dgvSubmittedReports.Refresh();
        }

        private void tbpExceptions_Enter(object sender, EventArgs e)
        {
            gvExceptions.Refresh();
        }

        private void tbpDataCount_Enter(object sender, EventArgs e)
        {
            dgvDataCounts.Refresh();
        }

        private void btnNewQuery_Click(object sender, EventArgs e)
        {
            txtQueryName.Clear();
            txtQueryDescription.Clear();
            sqlTextEditorSaveQuery.ResetText();
            txtQueryInternalName.Clear();
            txtQueryInternalName.Enabled = true;
            txtQueryInternalName.Tag = null;
            chbCreateTable.Checked = false;

            sqlTextEditor.ResetText();
            tabQueries.SelectedTab = tabPageQueriesDesign;
        }
      

        private void tabPageReportManagement_Enter(object sender, EventArgs e)
        {
            if (!tabPageReportManagementLoaded)
            {
                if ((AppConfiguration.AccessMethod == DataAccessMethod.OFFLINE_DATA_ACCESS) ||
                    (AppConfiguration.AccessMethod == DataAccessMethod.OFFLINE_DIRECT_ACCESS))
                {
                    tabReportManagement.TabPages.Remove(tabPageReportManagementReportMerge);
                }
                tabPageReportManagementLoaded = true;
            }
        }

        private void lblBRErrMsg_MouseHover(object sender, EventArgs e)
        {
            controlToolTip.SetToolTip(lblBRErrMsg, lblBRErrMsg.Text);
        }

        private void lblBRRepDetails_MouseHover(object sender, EventArgs e)
        {
            controlToolTip.SetToolTip(lblBRRepDetails, lblBRRepDetails.Text);
        }



        private void btnSMSUsersExportToExcel_Click(object sender, EventArgs e)
        {
            CreateExcelExportFile(this.SMSUsers);
        }
        
        //private void lblBRErrMsg_Paint(object sender, PaintEventArgs e)
        //{
        //    base.OnPaint(e);
        //    TextFormatFlags flags = TextFormatFlags.Bottom | TextFormatFlags.EndEllipsis;
        //    Rectangle labelSize = new Rectangle(lblBRErrMsg.Location, lblBRErrMsg.Size);
        //    TextRenderer.DrawText(e.Graphics, lblBRErrMsg.Text, this.Font, labelSize, SystemColors.ControlText, flags);
        //}

        #region Menu Items Event Handlers
        private void changePasswordToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ChangePassword changePassword = new ChangePassword(this.authenticatedUser);
            changePassword.ShowDialog(this);
        }

        private void logoutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
            this.m_LoggedOff = true;
        }

        private void setAutomaticSMSReminderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                var editor = new AutomaticSMSReminder();
                editor.ShowDialog();
            }
            catch (Exception ex)
            {
                DisplayErrorMessage(ex);
            }
        }

        private void viewHelpToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                string helpFile = String.Format(@"{0}\Resources\User Manual.chm", Application.StartupPath);
                System.Diagnostics.Process.Start(helpFile);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this,
                    String.Format("Could not open user guide.\n\n{0}", ex.Message),
                    "Error Opening Help", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void aboutIQSMSReportsManagementToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutIQSMS aboutIQSMS = new AboutIQSMS();
            aboutIQSMS.ShowDialog(this);
        }

        private void viewProfileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                UserDetails userDetails = new UserDetails(this.authenticatedUser, this.authenticatedUser);
                DialogResult response = userDetails.ShowDialog(this);
                if (response == System.Windows.Forms.DialogResult.OK)
                {
                    this.lblUser.Text = String.Format("Welcome {0}!", this.authenticatedUser.FullName);
                    this.welcomeAccountToolStripMenuItem.Text = String.Format("&Welcome {0}!", this.authenticatedUser.FullName);
                }
            }
            catch (Exception ex)
            {
                DisplayErrorMessage(ex);
            }
        }           

        private void setOtherSystemsFacilityDetailsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if ((AppConfiguration.AccessMethod == DataAccessMethod.OFFLINE_DATA_ACCESS) ||
                (AppConfiguration.AccessMethod == DataAccessMethod.OFFLINE_DIRECT_ACCESS))
            {
                string message = @"The application is running in offline mode. " +
                    "You can not perform any activities that require server " +
                    "connection while you are offline. " +
                    "\n\nYou are current operation will not be processed!";
                MessageBox.Show(this, message, AppConfiguration.ApplicationName,
                    MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }

            try
            {
                var editor = new OtherFacilityBasicDetails(this.authenticatedUser);
                editor.ShowDialog(this);
            }
            catch (Exception ex)
            {
                DisplayErrorMessage(ex);
            }
        }
        #endregion 

        private void btnAddReportMerge_Click(object sender, EventArgs e)
        {
            try
            {
                var mergingEditor = new Components.ReportMergingEditor();
                WindowInteropHelper helper = new WindowInteropHelper(mergingEditor);
                helper.Owner = this.Handle;
                bool? saved = mergingEditor.ShowDialog();
                if (saved.HasValue && saved.Value)
                {
                    // Reload the list to reflect the changes
                    tabPageReportManagementReportMergeLoaded = false;
                    tabPageReportManagementReportMerge_Enter(null, null);
                }
            }
            catch (Exception ex)
            {
                DisplayErrorMessage(ex);
            }
        }

        private void btnOptionBPlus_Click(object sender, EventArgs e)
        {
            try
            {
                if (radGridView1.SelectedRows.Count > 0)
                {
                    GridViewRowInfo row = radGridView1.SelectedRows[0];
                    GridViewCellInfo cell = row.Cells[0];
                    string facilityCode = row.Cells[0].Value.ToString();
                    string facilityName = row.Cells[1].Value.ToString();
                    string districtName = row.Cells[3].Value.ToString();
                    string regionName = row.Cells[4].Value.ToString();

                    var facilityInfo = Utilities.GetOptionBPlusFacilityInfo(facilityCode);
                    if (facilityInfo == null)
                    {
                        facilityInfo = new DataModels.Models.OptionBPlusFacility
                        {
                            FacilityCode = facilityCode,
                            HasCTC = false,
                            CTCStartDate = DateTime.Now,
                            DateStarted = DateTime.Now,
                            DateTrained = DateTime.Now
                        };
                    }
                    var editor = new OptionBPlusServiceProviderEditor(facilityInfo, facilityName, districtName, regionName);
                    WindowInteropHelper helper = new WindowInteropHelper(editor);
                    helper.Owner = this.Handle;
                    editor.ShowDialog();
                }
            }
            catch (Exception ex)
            {
                DisplayErrorMessage(ex);
            }
        }

        private void cbName_TextChanged(object sender, EventArgs e)
        {
            if (cbName.SelectedValue == null) btnGetReport.Enabled = false;
            else btnGetReport.Enabled = true;
        }

        


        private const int MAXIMUM_UPLOAD_TRIAL_ON_FAILED_ATTEMPTS = 10;
        private int offlineUploadingTrials = MAXIMUM_UPLOAD_TRIAL_ON_FAILED_ATTEMPTS;
        private void backgroundWorkerOfflineDataUploader_DoWork(object sender, DoWorkEventArgs e)
        {
            AppConfiguration.DetermineWebserviceAddress();
            if (AppConfiguration.AddressFound) Utilities.WebServicesURL = AppConfiguration.WebServiceURL;
            else
            {
                e.Cancel = true;
                return;
            }

            bool initialized = OfflineDataCapturing.InitializeOfflineDataSavingEnvironment();
            if (initialized)
            {
                bool atLeastOneUploaded = OfflineDataCapturing.UploadOfflineReportData(true);

                // Here if atleast one report is uploaded, then we are OK.
                // During the status display, we'll check to see how many left and give that notification
                // the user. If all went well we'll also tell the user.
                if (atLeastOneUploaded) offlineUploadingTrials = MAXIMUM_UPLOAD_TRIAL_ON_FAILED_ATTEMPTS;

                // BUT if no report has been uploaded, that is a clear sign that something is wrong.
                // Whether the report(s) was rejected by the server or connection error. We'll start to report
                // about this for MAXIMUM_UPLOAD_TRIAL_ON_FAILED_ATTEMPTS, and then we'll simply be quite [NO MORE BOTHERING]
                // until the user logs in again.
                else
                {
                    offlineUploadingTrials--;
                    if (offlineUploadingTrials > 0) e.Cancel = true;
                }
            }
        }

        private void offlineDataUploadingTimer_Tick(object sender, EventArgs e)
        {
            if (OfflineDataCapturing.AnyReportNeedsUploading())
            {
                if (!backgroundWorkerOfflineDataUploader.IsBusy)
                {
                    backgroundWorkerOfflineDataUploader.RunWorkerAsync();
                    //offlineDataUploadingTimer.Start();
                }
            }
        }

        private void backgroundWorkerOfflineDataUploader_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled) return;
            if (e.Error == null)
            {
                var erronousReports = OfflineDataCapturing.GetSkippedReports();
                if (erronousReports.Count > 0)
                {
                    StringBuilder sBuilder = new StringBuilder();
                    foreach (var report in erronousReports)
                    {
                        ReportingMessage info = (ReportingMessage)report.Tag;
                        string message = "Report: " + report.ReportName + Environment.NewLine
                            + "Facility: " + report.FacilityName + "[" + report.FacilityCode + "]" + Environment.NewLine
                            + "Month: " + report.ReportMonth + " Year: " + report.ReportYear + Environment.NewLine
                            + "Info: " + info.Message + Environment.NewLine + Environment.NewLine;
                        sBuilder.Append(message);
                    }

                    notifyIcon.BalloonTipTitle = "Offline data Uploading";
                    notifyIcon.BalloonTipText = sBuilder.ToString();
                    notifyIcon.BalloonTipIcon = ToolTipIcon.Warning;
                }
                else
                {
                    // Everything appears to be OK
                    notifyIcon.BalloonTipTitle = "Offline data uploading";
                    notifyIcon.BalloonTipText = "All reports have been successfully";
                    notifyIcon.BalloonTipIcon = ToolTipIcon.Info;
                    
                    // Don't we need just one?
                    offlineDataUploadingTimer.Enabled = false;
                    offlineDataUploadingTimer.Stop();
                }
            }
            else
            {
                notifyIcon.BalloonTipTitle = "Error Uploading offline data";
                notifyIcon.BalloonTipText = e.Error.Message;
                notifyIcon.BalloonTipIcon = ToolTipIcon.Error;
            }

            notifyIcon.ShowBalloonTip(10000);
        }

        private void MainWindow_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                OfflineDataCapturing.SaveOfflineData();
            }
            catch { }
        }

        private void notifyIcon_Click(object sender, EventArgs e)
        {
            notifyIcon.ShowBalloonTip(5000);
        }

        private void setDHIS2DatasetsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            WindowInteropHelper interopHelper = null;
            if (DHISDataBridge.DefaultAuthorizationAgent == null)
            {
                DHISDataBridge.DefaultBaseUrl = AppConfiguration.DHISBaseUrl;
                var dhisLogin = new DHISLogin();
                interopHelper = new WindowInteropHelper(dhisLogin);
                interopHelper.Owner = this.Handle;
                bool? result = dhisLogin.ShowDialog();

                if (result.HasValue && result.Value) DHISDataBridge.DefaultAuthorizationAgent = dhisLogin.Agent;
                else return;
            }

            var editor = new ReportingManagement.Components.DHIS.DHISDatasetConfiguration();
            interopHelper = new WindowInteropHelper(editor);
            interopHelper.Owner = this.Handle;
            editor.ShowDialog();
        }


        #region IQueryDesigner Implementation
        public void ShowInDesigner(string queryDefinition)
        {
            tabPageQueries_Enter(null, null);
            sqlTextEditor.Text = queryDefinition;
            tabQueries.SelectedTab = tabPageQueriesDesign;
            tabPageQueriesDesign.Show();
        }

        #endregion

        private void btnDHISCompare_Click(object sender, EventArgs e)
        {
            WindowInteropHelper interopHelper = null;
            if (DHISDataBridge.DefaultAuthorizationAgent == null)
            {
                DHISDataBridge.DefaultBaseUrl = AppConfiguration.DHISBaseUrl;
                var dhisLogin = new DHISLogin();
                interopHelper = new WindowInteropHelper(dhisLogin);
                interopHelper.Owner = this.Handle;
                bool? result = dhisLogin.ShowDialog();

                if (result.HasValue && result.Value) DHISDataBridge.DefaultAuthorizationAgent = dhisLogin.Agent;
                else return;
            }

            var comparer = new DatasetComparer(this.authenticatedUser);
            interopHelper = new WindowInteropHelper(comparer);
            interopHelper.Owner = this.Handle;
            comparer.ShowDialog();
        }

        private void btnClearAllBlockedUsers_Click(object sender, EventArgs e)
        {
            if ((AppConfiguration.AccessMethod == DataAccessMethod.OFFLINE_DATA_ACCESS) ||
                (AppConfiguration.AccessMethod == DataAccessMethod.OFFLINE_DIRECT_ACCESS))
            {
                string message = @"The application is running in offline mode. " +
                    "You can not perform any activities that require server " +
                    "connection while you are offline. " +
                    "\n\nYou are current operation will not be processed!";
                MessageBox.Show(this, message, AppConfiguration.ApplicationName,
                    MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }

            DialogResult response = MessageBox.Show(this,
                String.Format("Do you want to clear all blocked users?"),
                String.Format("{0} - Unblock Report", AppConfiguration.ApplicationName),
                MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (response == System.Windows.Forms.DialogResult.Yes)
            {
                DataGridViewRow dgvDetails = dgvBlockedReports.CurrentRow;
                string senderNumber = dgvDetails.Cells["SenderNum"].Value.ToString();
                //int report = Int32.Parse(dgvDetails.Cells["RepID"].Value.ToString());
                //string facilityCode = dgvDetails.Cells["FacCode"].Value.ToString();
                //int year = Int32.Parse(dgvDetails.Cells["Year"].Value.ToString());
                //int period = Int32.Parse(dgvDetails.Cells["Period"].Value.ToString());

                try
                {
                    Cursor.Current = Cursors.WaitCursor;
                    cmdUnblock.Enabled = false;
                    toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
                    //Utilities.DeleteBlockedReport(report, facilityCode, period, year);
                    Utilities.DeleteBlockedUserReport(senderNumber);

                    //string filterExpression = String.Format("SenderNum = {0}", senderNumber);
                    //DataRow[] rows = blockedReports.Select(filterExpression);
                    //for (int i = 0; i < rows.Length; i++) blockedReports.Rows.Remove(rows[i]);

                    //List<DataRow> rowsToDelete = new List<DataRow>();
                    //for (int i = 0; i < blockedReports.Rows.Count; i++)
                    //{
                    //    DataRow row = blockedReports.Rows[i];
                    //    string number = row["SenderNum"].ToString();
                    //    if (number == senderNumber) rowsToDelete.Add(row);
                    //}
                    //for (int i = 0; i < rowsToDelete.Count; i++) blockedReports.Rows.Remove(rowsToDelete[i]);

                    //PopulateBlockedReports();
                    //cmdUnblock.Enabled = true;

                    foreach (DataGridViewRow r in dgvBlockedReports.Rows)
                    {
                        DataRowView rowView = r.DataBoundItem as DataRowView;
                        if (rowView != null)
                        {
                            string number = rowView["SenderNum"].ToString();
                            if (number == senderNumber) rowView.Delete();
                        }
                    }
                    Cursor.Current = Cursors.Default;
                    toolStripStatusLabel.Text = "Ready";
                    cmdUnblock.Enabled = (dgvBlockedReports.Rows.Count > 0);
                    if (string.IsNullOrEmpty(txtSearchBlockedReports.Text))
                    {
                        lblBlockedCount.Text = String.Format("There are {0} blocked reporting",
                            dgvBlockedReports.Rows.Count);
                        lblBlockedCount.ForeColor = Color.Black;
                    }
                    else
                    {
                        lblBlockedCount.Text = string.Format("Search Results: {0} blocked reporting", dgvBlockedReports.Rows.Count);
                        lblBlockedCount.ForeColor = Color.BlueViolet;
                    }


                    //Cursor.Current = Cursors.WaitCursor;
                    //toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();                    

                    //if (AppConfiguration.DataCached) dgvBlockedReports.Rows.Remove(dgvDetails);
                    //else
                    //{
                    //    Cursor.Current = Cursors.WaitCursor;
                    //    toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
                    //    dtErrReps = Utilities.GetBlockedReports();
                    //    PopulateBlockedReports(dtErrReps);
                    //    Cursor.Current = Cursors.Default;
                    //    toolStripStatusLabel.Text = "Ready";
                    //}
                }
                catch (Exception ex)
                {
                    DisplayErrorMessage(ex);
                }
            }
        }
    }
}
